package com.echo.im.infrastructure.session;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存储用户对应的 Channel
 * @author echo
 */
public class UserChannelMap {

    /**
     *  维护userId和ctx的关联关系，格式:Map<userId,map<terminal，ctx>>
     */
    private static final Map<Long, Map<Integer, Channel>> CHANNEL_MAP = new ConcurrentHashMap<>();

    public static void addChannel(Long userId, Integer channel, Channel ctx) {
        CHANNEL_MAP.computeIfAbsent(userId, key -> new ConcurrentHashMap<>()).put(channel, ctx);
    }

    public static void removeChannel(Long userId, Integer terminal) {
        if (userId != null && terminal != null && CHANNEL_MAP.containsKey(userId)) {
            Map<Integer, Channel> userChannelMap = CHANNEL_MAP.get(userId);
            userChannelMap.remove(terminal);
        }
    }

    public static Channel getChannel(Long userId, Integer terminal) {
        if (userId != null && terminal != null && CHANNEL_MAP.containsKey(userId)) {
            Map<Integer, Channel> userChannelMap = CHANNEL_MAP.get(userId);
            if (userChannelMap.containsKey(terminal)) {
                return userChannelMap.get(terminal);
            }
        }
        return null;
    }

    public static Map<Integer, Channel> getChannel(Long userId) {
        if (userId == null) {
            return null;
        }
        return CHANNEL_MAP.get(userId);
    }

    public static Channel getChannelByChannelShortId(Long userId, String channelShortId) {

        Map<Integer, Channel> integerChannelMap = CHANNEL_MAP.get(userId);
        for (Channel channel:integerChannelMap.values()){
            if (channel.id().asShortText().equals(channelShortId)){
                return channel;
            }
        }
        return null;
    }
}
